package com.cskaoyan.util;

import com.cskaoyan.bean.vo.BaseRespVo;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatchUtil {

    public static void dispatch(String operation, HttpServletRequest request, HttpServletResponse response, HttpServlet instance) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
        Method method = instance.getClass().getDeclaredMethod(operation,HttpServletRequest.class,HttpServletResponse.class);
        method.setAccessible(true);
        // 执行到了Servlet中的方法 → returnValue就是方法的返回值
        Object returnValue = method.invoke(instance, new Object[]{request, response});
        // 执行完方法响应JSON字符串
        if (returnValue != null && returnValue instanceof BaseRespVo<?>) {

            ResponseUtil.responseJson(response,returnValue);
        }
    }
}
